<template>
  <div class="my-quill-editor">
    <a-upload
      id="imageUpload"
      accept="image/*"
      name="file"
      class="uploadImage"
    >
    </a-upload>

    <quill-editor
      class="ql-editor"
      ref="myQuillEditor"
      :value="contentMain"
      :options="editorOption"
      @change="onEditorChange($event)"
      @ready="onEditorReady($event)"
    />
    <!-- <div v-if="lengthMax > 0" class="lengthMax">内容最多 <span class="text">{{ lengthMax }}</span> 字</div> -->
    <div v-if="lengthMax > 0" class="textRemain">{{ currentLength }}/{{ lengthMax }}</div>
  </div>
</template>
<script>
import { uploadFile } from '@/api/organization/organization'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor, Quill } from 'vue-quill-editor'
// QuillWatch
import { container, ImageExtend } from 'quill-image-extend-module'

import { message } from 'ant-design-vue'
// import { dealImageUrl } from '@/utils/filter'
Quill.register('modules/ImageExtend', ImageExtend)
const headers = {
  'image': function (value) {
    const self = this
    let fileInput = this.container.querySelector('input.ql-image[type=file]')
    if (fileInput === null) {
      fileInput = document.createElement('input')
      fileInput.setAttribute('type', 'file')
      // 设置图片参数名
      fileInput.setAttribute('name', 'file')
      // 可设置上传图片的格式
      fileInput.setAttribute('accept', 'image/*')
      fileInput.classList.add('ql-image')
      // 监听选择文件
      fileInput.addEventListener('change', function () {
        // 创建formData
        const formData = new FormData()

        if (!fileInput.files[0].type.match(/^image\/(gif|jpe?g|a?png|bmp|webp)/i)) {
          message.error(self.$t('all.autotext1561'))
          return
        }
        formData.append('file', fileInput.files[0])
        // 如果需要token且存在token
        // if (uploadConfig.token) {
        //     formData.append('token', uploadConfig.token)
        // }
        // 图片上传
        const xhr = new XMLHttpRequest()
        xhr.open('POST', '/api/common/upload', true)
        // 上传数据成功，会触发
        xhr.onload = function (e) {
          // console.log('富文本', self.quill)
          if (xhr.status === 200 && xhr.responseText) {
            const result = JSON.parse(xhr.responseText)
            if (result.status === '1' && result.data) {
              // console.log('文件路径', (process.env.VUE_APP_BASE_IMAGE + result.data))
              const length = self.quill.getSelection(true).index
              // console.log('length', length)
              // // 这里很重要，你图片上传成功后，img的src需要在这里添加，res.path就是你服务器返回的图片链接。
              console.log(process.env)
              self.quill.insertEmbed(length, 'image', (process.env.VUE_APP_BASE_IMAGE + result.data))
              self.quill.setSelection(length + 1)
            }
          // var res = JSON.parse(xhr.responseText)
          // const length = self.quill.getSelection(true).index
          // // 这里很重要，你图片上传成功后，img的src需要在这里添加，res.path就是你服务器返回的图片链接。
          // self.quill.insertEmbed(length, 'image', res.path)
          // self.quill.setSelection(length + 1)
          }
          fileInput.value = ''
        }
        // 开始上传数据
        xhr.upload.onloadstart = function (e) {
          fileInput.value = ''
        }
        // 当发生网络异常的时候会触发，如果上传数据的过程还未结束
        xhr.upload.onerror = function (e) {
        }
        // 上传数据完成（成功或者失败）时会触发
        xhr.upload.onloadend = function (e) {
        // console.log('上传结束')
        }
        xhr.send(formData)
      })
      this.container.appendChild(fileInput)
    }
    fileInput.click()
  // QuillWatch.emit(this.quill.id)
  }
}
export default {
  components: { quillEditor },
  props: {
    content: {
      default: '',
      type: String
    },
    lengthMax: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      currentLength: 0,
      contentMain: '',
      // content:"",
      editorOption: {
        modules: {
          clipboard: {
            matchers: [
              // ['img', this.handleCustomMatcher]
            ]
          },
          ImageExtend: {
            loading: true,
            name: 'file',
            size: 2,
            action: '/api/common/upload',
            response: (res) => {
              const { status, data } = res
              if (status === '1' && data) {
                return this.$options.filters.dealImageUrl(data)
              } else {
                this.$message(this.$t('all.autotext1562'))
              }
            }
          },
          toolbar: {
            container: container,
            handlers: headers
          }
        }
      }
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
  mounted () {
    this.init()
    this.$nextTick(() => {
      this.contentMain = this.content
      this.editor.root.addEventListener('paste', evt => {
        if (evt.clipboardData && evt.clipboardData.files && evt.clipboardData.files.length) {
          evt.preventDefault();
          [].forEach.call(evt.clipboardData.files, file => {
            if (file.type.match(/^image\/(gif|jpe?g|a?png|bmp|webp)/i)) {
              const params = new FormData()
              params.append('file', file)
              uploadFile(params).then(result => {
                const length = this.editor.getSelection(true).index
                this.editor.insertEmbed(length, 'image', (process.env.VUE_APP_BASE_IMAGE + result))
                this.editor.setSelection(length + 1)
              })
            }
          })
        }
      })
    }, false)
  },

  methods: {
    init () {
      setTimeout(() => {
        // this.currentLength = this.content ? this.content.length : 0
        // this.$refs.myQuillEditor.quill.getLength() - 1
        this.currentLength = this.$refs.myQuillEditor.quill.getLength() - 1
        this.updateLength()
      }, 100)
    },
    onEditorChange (event) {
      // this.$refs.myQuillEditor.quill.deleteText(8, 8)
      this.$emit('editChange', event.html)
      this.currentLength = this.$refs.myQuillEditor.quill.getLength() - 1
      this.updateLength()
    },
    onEditorReady (event) {
      // this.$refs.myQuillEditor.quill.deleteText(8, 8)
      this.$emit('editorReady', event.html)
      this.currentLength = this.$refs.myQuillEditor.quill.getLength() - 1
      this.updateLength()
    },
    updateLength () {
      this.$emit('updateLength', this.currentLength)
    }
  }
}
</script>

<style>
  .editor-upload{
    display: none;
  }
  .my-quill-editor{
    line-height: 22px;
  }
  .my-quill-editor .ql-container{
    min-height:300px;
    font-size: 16px !important;
  }
  .uploadImage,
  .uploadFile{
    width: 0;
    height: 0;
    display: none;
  }
  .textRemain{
    text-align: right;
    padding-right: 15px;
  }
  .lengthMax{
    padding-left: 15px;
  }
  .text{
    color: #ff0000;
  }

</style>
